package com.example.topguli;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Constomsocket {
    private Integer flag = 1;
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();

    public static void main(String[] args) {
        Constomsocket constomsocket = new Constomsocket();
        for (Integer i = 0; i < 3; i++) {
            new Thread(() -> {
                constomsocket.A();
                constomsocket.B();
                constomsocket.C();
            }, i.toString()).start();
        }
    }

    public void A() {
        lock.lock();
        try {
            while (flag == 1) {
                for (int i = 0; i < 5; i++) {
                    System.out.println(Thread.currentThread().getName() + "====>"+i);
                }
                flag=2;
                condition.await();
            }
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void B() {
        lock.lock();
        try {
            while (flag == 2) {
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName() + "====>"+i);
                }
                flag=3;
                condition1.await();
            }
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

        public void C() {
            lock.lock();
            try {
                while (flag == 3) {
                    for (int i = 0; i < 15; i++) {
                        System.out.println(Thread.currentThread().getName() + "====>"+i);
                    }
                    flag=1;
                    condition2.await();
                }
                condition1.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

